﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.EFDBFirst;
using YiYiTong.Rocket.Model;
using System.ComponentModel;
using YiYiTong.Rocket.Model.Manager;
using YiYiTong.Rocket.Business;
using System.Text.RegularExpressions;
using System.Text;
using YiYiTong.Rocket.Business.Biz;
using System.Data;
using YiYiTong.Rocket.Model.ParamModel;

namespace YiYiTong.Rocket.ManageWeb.Controllers
{
    public class AccountController : BaseController
    {
        #region 会员
        [Description("会员列表")]
        [ViewPage]
        public ActionResult AccountList(AccountListModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;

            var queryable = GetAccountList(queryModel);

            //数据统计
            int rowcounts = queryable.Count();
            decimal? allbalance = queryable.Sum(t => t.account_balance);
            ViewData.Add("AllCount", rowcounts);
            ViewData.Add("AllBalance", allbalance);
            //分页
            var querylist = queryable.OrderByDescending(t => t.create_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<View_Member> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<View_Member>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [NoVerify]
        public ActionResult DownAccountList(AccountListModel queryModel)
        {
            queryModel.Trim();
            var queryable = GetAccountList(queryModel);

            var querylist = queryable.OrderByDescending(t => t.uid).ToList();

            string strOutPut = string.Empty;
            string Excel = AccountListExcel(querylist, out strOutPut);
            ResponseMsg resMsg = new ResponseMsg();
            if (strOutPut != "导出成功")
            {
                resMsg.IsSuccess = false;
                resMsg.Message = strOutPut;

                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            byte[] fileContents = Encoding.UTF8.GetBytes(Excel.ToString());
            return File(fileContents, "application/ms-excel", "accountlist_" + DateTime.Now.ToString(4) + ".xls");
        }

        public string AccountListExcel(List<View_Member> listmodel, out string strOutPut)
        {
            List<string> list_title = new List<string> {
                "姓名",
                "性别",
                "公司名",
                "地址",
                "联系方式",
                "关注品牌",
                "关注品类",
                "负责人",
                "客户类型",
                "代购编号",
                "会员手机号",
                "会员名称",
                "会员等级",
                "推荐人",
                "推荐人手机号",
                "会员状态",
                "注册时间",
                "余额",
                "代购比例",
                "推荐比例",
                "加价比例",
                "备注信息"
            };
            ExportExcel Excel = new ExportExcel();
            DataTable dt = new DataTable();
            list_title.ForEach(t => dt.Columns.Add(t));
            dt.Columns["姓名"].DataType = typeof(StringNumber);
            dt.Columns["公司名"].DataType = typeof(StringNumber);
            dt.Columns["地址"].DataType = typeof(StringNumber);
            dt.Columns["联系方式"].DataType = typeof(StringNumber);
            dt.Columns["关注品牌"].DataType = typeof(StringNumber);
            dt.Columns["关注品类"].DataType = typeof(StringNumber);
            dt.Columns["客户类型"].DataType = typeof(StringNumber);

            dt.Columns["代购编号"].DataType = typeof(StringNumber);
            dt.Columns["会员手机号"].DataType = typeof(StringNumber);
            dt.Columns["会员名称"].DataType = typeof(StringNumber);
            dt.Columns["推荐人"].DataType = typeof(StringNumber);
            dt.Columns["推荐人手机号"].DataType = typeof(StringNumber);
            dt.Columns["余额"].DataType = typeof(StringNumber);
            dt.Columns["代购比例"].DataType = typeof(StringNumber);
            dt.Columns["推荐比例"].DataType = typeof(StringNumber);
            dt.Columns["加价比例"].DataType = typeof(StringNumber);
            dt.Columns["负责人"].DataType = typeof(StringNumber);
            dt.Columns["备注信息"].DataType = typeof(StringNumber);
            if (!listmodel.Any())
            {
                return Excel.DtToExcel(dt, list_title, out strOutPut);
            }


            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var brand_list = dbcontext.ADZ_BrandMaster.Where(t => t.is_del == 0).ToList();
            var category_list = dbcontext.ADZ_GoodsCategory.Where(t => t.is_del == 0).ToList();
            var followlist = dbcontext.ADZ_MemberFollow.ToList();

            for (int i = 0; i < listmodel.Count; i++)
            {
                DataRow dr = dt.NewRow();

                dr["姓名"] = StringNumber.Crt(listmodel[i].real_name);
                dr["性别"] = (!listmodel[i].sex.HasValue) ? "未知" : (listmodel[i].sex.Value == 0 ? "女" : "男");
                dr["公司名"] = StringNumber.Crt(listmodel[i].company_name);
                dr["地址"] = StringNumber.Crt(listmodel[i].address);
                dr["联系方式"] = StringNumber.Crt(listmodel[i].company_telephone);

                ////关注品牌
                var user_brand_list = (from tba in brand_list
                                       join tbb in followlist
                                       on tba.brand_id equals tbb.follow_id
                                       where tbb.uid == listmodel[i].uid && tbb.follow_type == 2
                                       select new
                                       {
                                           tba.brand_name
                                       }).ToList();
                string user_brand_name = "";
                foreach (var item in user_brand_list)
                {
                    user_brand_name += item.brand_name + ",";
                }
                if (!string.IsNullOrWhiteSpace(user_brand_name))
                    user_brand_name = user_brand_name.Substring(0, user_brand_name.Length - 1);
                ////关注品类
                var user_category_list = (from tba in category_list
                                          join tbb in followlist
                                       on tba.category_id equals tbb.follow_id
                                          where tbb.uid == listmodel[i].uid && tbb.follow_type == 1
                                          select new
                                          {
                                              tba.category_name
                                          }).ToList();
                string user_category_name = "";
                foreach (var item in user_category_list)
                {
                    user_category_name += item.category_name + ",";
                }
                if (!string.IsNullOrWhiteSpace(user_category_name))
                    user_category_name = user_category_name.Substring(0, user_category_name.Length - 1);


                dr["关注品牌"] = StringNumber.Crt(user_brand_name);
                dr["关注品类"] = StringNumber.Crt(user_category_name);

                dr["代购编号"] = StringNumber.Crt(listmodel[i].replace_buyer_NO);
                dr["会员手机号"] = StringNumber.Crt(listmodel[i].account_mobile);
                dr["会员名称"] = StringNumber.Crt(listmodel[i].member_name);
                dr["会员等级"] = listmodel[i].member_level_name;
                dr["会员状态"] = listmodel[i].account_status == 0 ? "正常" : "停用";
                dr["注册时间"] = listmodel[i].create_time.ToString(1);
                dr["余额"] = StringNumber.Crt(listmodel[i].account_balance);
                dr["代购比例"] = StringNumber.Crt(listmodel[i].buyer_rate);
                dr["推荐比例"] = StringNumber.Crt(listmodel[i].recommend_rate);
                dr["加价比例"] = StringNumber.Crt(listmodel[i].add_rate);

                //查找推荐人
                long uid = listmodel[i].uid;
                var result = AccountBiz.Instance.GetRecommend(uid, dbcontext);
                dr["推荐人"] = StringNumber.Crt(result.Item2);
                dr["推荐人手机号"] = StringNumber.Crt(result.Item3);

                //查找业务员
                var managerUid = listmodel[i].manage_uid;
                string userName = "";
                if (managerUid.HasValue && managerUid.Value > 0)
                {
                    var managerUser = UserBiz.Instance.GetUserInfoById(managerUid.Value);
                    if (managerUser != null)
                        userName = managerUser.realName;
                }
                dr["负责人"] = StringNumber.Crt(userName);


                dr["客户类型"] = StringNumber.Crt(listmodel[i].customer_type_name);
                dr["备注信息"] = StringNumber.Crt(listmodel[i].remark);

                dt.Rows.Add(dr);
            }

            return Excel.DtToExcel(dt, list_title, out strOutPut);
        }

        private IQueryable<View_Member> GetAccountList(AccountListModel queryModel)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            //条件筛选
            var queryable = dbcontext.View_Member.Where(t => t.is_del == 0);
            if (!string.IsNullOrWhiteSpace(queryModel.account_mobile))
                queryable = queryable.Where(t => t.account_mobile == queryModel.account_mobile);
            if (!string.IsNullOrWhiteSpace(queryModel.member_name))
                queryable = queryable.Where(t => t.member_name.Contains(queryModel.member_name));
            if (!string.IsNullOrWhiteSpace(queryModel.replace_buyer_NO))
                queryable = queryable.Where(t => t.replace_buyer_NO == queryModel.replace_buyer_NO);
            if (queryModel.account_status != -10)
                queryable = queryable.Where(t => t.account_status == queryModel.account_status);
            if (queryModel.member_level != -10)
                queryable = queryable.Where(t => t.member_level == queryModel.member_level);
            if (queryModel.beg_time.HasValue)
                queryable = queryable.Where(t => t.create_time >= queryModel.beg_time);
            if (queryModel.end_time.HasValue)
            {
                var end_time = queryModel.end_time.Value.AddDays(1);
                queryable = queryable.Where(t => t.create_time < end_time);
            }

            long manager_uid = 0;
            if (!string.IsNullOrWhiteSpace(queryModel.manager_name))
            {
                string[] id_arr = Regex.Split(queryModel.manager_name, "-");
                manager_uid = ConvertHelper.ConvertTo<long>(id_arr[id_arr.Length - 1], 0);
            }
            if (manager_uid > 0)
            {
                queryable = queryable.Where(t => t.manage_uid == manager_uid);
            }
            return queryable;
        }

        [Description("会员详情")]
        [ViewPage]
        public ActionResult DefailInfo(long uid = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            AccountDefailModel model = new AccountDefailModel();
            if (uid > 0)
            {
                View_Member member = dbcontext.View_Member.FirstOrDefault(t => t.uid == uid && t.is_del == 0);
                List<ADZ_UserAddress> addressList = dbcontext.ADZ_UserAddress.Where(t => t.uid == uid).OrderByDescending(t => t.is_default).ToList();
                List<ADZ_UserInvoice> invoiceList = dbcontext.ADZ_UserInvoice.Where(t => t.uid == uid).ToList();
                model.member = member;
                model.invoiceList = invoiceList;
                model.addressList = addressList;
            }
            return View(model);
        }

        [Description("资金明细")]
        [ViewPage]
        public ActionResult AmountLogList(AmountLogListModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            //条件筛选
            var queryable = dbcontext.View_AmountLog.Where(t => t.is_del == 0);
            if (!string.IsNullOrWhiteSpace(queryModel.account_mobile))
                queryable = queryable.Where(t => t.account_mobile == queryModel.account_mobile);
            if (!string.IsNullOrWhiteSpace(queryModel.member_name))
                queryable = queryable.Where(t => t.member_name.Contains(queryModel.member_name));
            if (!string.IsNullOrWhiteSpace(queryModel.replace_buyer_NO))
                queryable = queryable.Where(t => t.replace_buyer_NO == queryModel.replace_buyer_NO);
            if (queryModel.uid != -10)
                queryable = queryable.Where(t => t.uid == queryModel.uid);
            if (queryModel.order_type != -10)
                queryable = queryable.Where(t => t.order_type == queryModel.order_type);
            if (queryModel.beg_time.HasValue)
                queryable = queryable.Where(t => t.create_time >= queryModel.beg_time);
            if (queryModel.end_time.HasValue)
            {
                var end_time = queryModel.end_time.Value.AddSeconds(1);
                queryable = queryable.Where(t => t.create_time < end_time);
            }

            //分页
            int rowcounts = queryable.Count();
            ViewData.Add("AllCount", rowcounts);
            var querylist = queryable.OrderByDescending(t => t.create_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<View_AmountLog> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<View_AmountLog>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [Description("禁用会员")]
        [HttpPost]
        public ActionResult ToForbidden(int uid = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var entity = dbcontext.ADZ_MemberMaster.FirstOrDefault(t => t.uid == uid);
            if (entity != null)
            {
                entity.account_status = 9;
                if (dbcontext.SaveChanges() > 0)
                {
                    //清除token
                    OAuthBiz.Instance.RemoveToken(uid);
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                }
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("启用会员")]
        [HttpPost]
        public ActionResult ToEnable(int uid = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var entity = dbcontext.ADZ_MemberMaster.FirstOrDefault(t => t.uid == uid);
            if (entity != null)
            {
                entity.account_status = 0;
                if (dbcontext.SaveChanges() > 0)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                }
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("提升等级")]
        [ViewPage]
        public ActionResult UpLevel(int uid = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            View_Member member = new View_Member();
            if (uid > 0)
                member = dbcontext.View_Member.FirstOrDefault(t => t.uid == uid && t.is_del == 0);
            return View(member);
        }

        [Description("提升等级")]
        [HttpPost]
        public ActionResult UpLevel(int uid, byte member_level)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var aDZ_MemberLevelConfig = dbcontext.ADZ_MemberLevelConfig.FirstOrDefault(t => t.member_level == member_level);
            if (aDZ_MemberLevelConfig == null)
            {
                resMsg.Message = "会员等级信息有误";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            //false表示降级
            bool upOrDown = false;
            var entity = dbcontext.ADZ_MemberMaster.FirstOrDefault(t => t.uid == uid);
            if (entity != null)
            {
                if (member_level != entity.member_level)
                {

                    dbcontext.ADZ_MemberLevelLog.Add(new ADZ_MemberLevelLog
                    {
                        create_time = DateTime.Now,
                        uid = uid,
                        old_level = entity.member_level,
                        new_level = member_level,
                        msg = $"等级变为{aDZ_MemberLevelConfig.member_name}",
                        opuser = new CurrentUser().user.loginName
                    });

                    upOrDown = (member_level > entity.member_level);
                    entity.member_level = member_level;
                    //等级提升昵称一并修改，等级名称+手机号格式 by leev 2019-03-13
                    Regex reg = new Regex(@"^[\u4E00-\u9FA5]{4}[0-9]{11}$");
                    //4个汉字+11位数字匹配
                    if (reg.IsMatch(entity.member_name))
                        entity.member_name = aDZ_MemberLevelConfig.member_name.Substring(0, 4) + entity.account_mobile;
                    dbcontext.SaveChanges();



                    ///如果有升级申请，一并处理掉
                    var upentity = dbcontext.ADZ_MemberUpApply.FirstOrDefault(t => t.uid == uid && t.is_do == 0);
                    if (upentity != null)
                    {
                        upentity.is_do = 1;
                        upentity.do_time = DateTime.Now;
                        upentity.do_name = new CurrentUser().user.realName;
                        upentity.remark = $"{new CurrentUser().user.realName}审核通过";
                        dbcontext.SaveChanges();
                    }

                    //提升会员等级后清除token，让用户重新登录
                    OAuthBiz.Instance.RemoveToken(uid);

                    //清除邀请码
                    dbcontext.ADZ_InviteCode.RemoveRange(dbcontext.ADZ_InviteCode.Where(t => t.uid == uid && t.is_used == 0));
                    dbcontext.SaveChanges();

                    //提升到共生会员自动生成邀请码 2019-02-22 leev
                    if (member_level == 20)
                    {
                        var result = AccountBiz.Instance.BuildInviteCode(uid);
                        if (!result.Item1)
                            LogHelper.Error("提升到共生会员自动生成邀请码错误，错误原因：" + result.Item2);
                    }

                    AddPushMsgModel paramModel = new AddPushMsgModel
                    {
                        aDZ_Pushmessage = new ADZ_Pushmessage
                        {
                            MsgType = 2,
                            ReceiveType = 1
                        },
                        ReceiveUids = entity.uid.ToString()
                    };
                    //发送推送消息
                    if (upOrDown)
                    {
                        paramModel.aDZ_Pushmessage.MsgTitle = "会员升级成功";
                        paramModel.aDZ_Pushmessage.MsgText = $"您的会员等级已经成功提升为{aDZ_MemberLevelConfig.member_name},您将享受{aDZ_MemberLevelConfig.member_name}给您带来的权益。";
                    }
                    else
                    {
                        paramModel.aDZ_Pushmessage.MsgTitle = "会员降级成功";
                        paramModel.aDZ_Pushmessage.MsgText = $"您的会员等级已经被降为{aDZ_MemberLevelConfig.member_name},如有疑问请联系客服。";
                    }
                    PushMsgBiz.Instance.AddPushMsg(paramModel);

                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功，请让用户重新登录";
                }
                else if (member_level == entity.member_level)
                    resMsg.Message = "操作失败,无需提升";
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("拒绝等级提升申请")]
        [HttpPost]
        public ActionResult UpLevelRefuse(long id, string remark)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();


            ///如果有升级申请，一并处理掉
            var upentity = dbcontext.ADZ_MemberUpApply.FirstOrDefault(t => t.seq_id == id && t.is_do == 0);
            if (upentity != null)
            {
                upentity.is_do = 2;
                upentity.do_time = DateTime.Now;
                upentity.do_name = new CurrentUser().user.realName;
                upentity.remark = $"拒绝原因：{remark}";

                dbcontext.SaveChanges();

                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
            }

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult SaveDefails(long uid, string real_name, short sex, string company_name, string address,
            string id_number, string contact_mobile, string company_telephone, string company_address, int customer_type
            , string remark)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            var result = AccountBiz.Instance.SaveDetails(uid, real_name, sex, company_name, address, id_number, contact_mobile, company_telephone, company_address, customer_type, remark);
            if (result.Item1)
            {
                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
            }
            else
                resMsg.Message = result.Item2;
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 邀请码
        [Description("邀请码列表")]
        [ViewPage]
        public ActionResult InviteCodeList(AccDefailQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            #region 邀请码分页
            var queryable = dbcontext.View_InviteCode.Where(t => t.is_del == 0);
            //条件筛选
            if (queryModel.uid != -10)
                queryable = queryable.Where(t => t.uid == queryModel.uid);
            if (queryModel.is_used != -10)
                queryable = queryable.Where(t => t.is_used == queryModel.is_used);

            int rowcounts = queryable.Count();
            ViewData.Add("AllCount", rowcounts);
            var querylist = queryable.OrderByDescending(t => t.create_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<View_InviteCode> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<View_InviteCode>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            #endregion
            return View(pagedlist);
        }

        [Description("生成邀请码")]
        [ViewPage]
        public ActionResult BuildCodePage(long uid = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            View_Member member = new View_Member();
            if (uid > 0)
                member = dbcontext.View_Member.FirstOrDefault(t => t.uid == uid && t.is_del == 0);

            return View(member);
        }

        [Description("生成邀请码")]
        [HttpPost]
        public ActionResult BuildCode(long uid = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            var result = AccountBiz.Instance.BuildInviteCode(uid);
            if (result.Item1)
                resMsg.IsSuccess = true;
            resMsg.Message = result.Item2;
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 我是卖家
        /// <summary>
        /// 卖家申请列表
        /// </summary>
        /// <param name="queryModel"></param>
        /// <returns></returns>
        [Description("卖家申请列表")]
        [ViewPage]
        public ActionResult SellerApplyList(SellerApplyQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            //条件筛选
            var queryable = dbcontext.View_SellerApply.Where(t => t.is_del == 0);
            if (queryModel.uid != -10)
                queryable = queryable.Where(t => t.uid == queryModel.uid);
            if (!string.IsNullOrWhiteSpace(queryModel.mobile))
                queryable = queryable.Where(t => t.account_mobile == queryModel.mobile);
            if (queryModel.beg_time.HasValue)
                queryable = queryable.Where(t => t.create_time >= queryModel.beg_time);
            if (queryModel.end_time.HasValue)
            {
                var end_time = queryModel.end_time.Value.AddDays(1);
                queryable = queryable.Where(t => t.create_time < end_time);
            }
            if (queryModel.is_do != -10)
                queryable = queryable.Where(t => t.is_do == queryModel.is_do);

            int rowcounts = queryable.Count();
            ViewData.Add("AllCount", rowcounts);
            var querylist = queryable.OrderByDescending(t => t.create_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<View_SellerApply> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<View_SellerApply>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [Description("卖家申请详情")]
        [ViewPage]
        public ActionResult SellerApplyInfo(long seq_id)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            //条件筛选
            View_SellerApply model = dbcontext.View_SellerApply.FirstOrDefault(t => t.seq_id == seq_id);
            return View(model);
        }
        [Description("修改卖家申请详情")]
        [HttpPost]
        public ActionResult SellerApplyInfo(EditSellerApplyModel paramModel)
        {
            long seq_id = paramModel.seq_id;
            ResponseMsg resMsg = new ResponseMsg();
            if (!ModelState.IsValid)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = ModelState.Values.First().Errors[0].ErrorMessage;
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            paramModel.Trim();
            ViewBag.ParamModel = paramModel;

            //todo 逻辑错误
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var aDZ_SellerApply = dbcontext.ADZ_SellerApply.FirstOrDefault(t => t.seq_id == seq_id);


            var listExcept = new List<String>();// { "uid", "seq_id", "sex", "create_time", "is_do", "do_time", "supplier_id", "is_agreement", "apply_status", "apply_step" };
            Utils.Mapper(aDZ_SellerApply, paramModel, listExcept, false);

            try
            {
                aDZ_SellerApply.supplier_type_name = dbcontext.ADZ_SupplierType.FirstOrDefault(t => t.supplier_type == aDZ_SellerApply.supplier_type).supplier_type_name;
            }
            catch { aDZ_SellerApply.supplier_type_name = ""; }
            aDZ_SellerApply.category_json = string.Join(",", paramModel.category_jsons);

            ///以下添加新图片
            HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            if (hfc != null && hfc.Count > 0)
            {
                for (int i = 0; i < hfc.Count; i++)
                {
                    var file = hfc[i];
                    var putResult = ImageFileBiz.UpImg(file);
                    if (!putResult.Item1)
                    {
                        resMsg.Message += (putResult.Item2);
                    }
                    else
                    {
                        aDZ_SellerApply.company_img = putResult.Item3;
                    }
                }
            }

            dbcontext.SaveChanges();

            resMsg.IsSuccess = true;
            resMsg.Message = "操作成功";

            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("卖家处理")]
        [HttpPost]
        public ActionResult ToDoBySeller(long id = 0, int is_refused = 0, string reson = "")
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var entity = dbcontext.ADZ_SellerApply.FirstOrDefault(t => t.seq_id == id);
            if (entity != null)
            {
                //拒绝审核
                if (is_refused == 1)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                    entity.refuse_reson = reson;
                    entity.apply_status = 2;
                    entity.apply_step = 5;
                    entity.do_time = DateTime.Now;
                    dbcontext.SaveChanges();

                    //审核驳回，推送消息
                    string msg = $"您的卖家申请审核未通过，原因是：{reson}";
                    AddPushMsgModel pushModel = new AddPushMsgModel
                    {
                        aDZ_Pushmessage = new ADZ_Pushmessage
                        {
                            MsgType = 2,
                            ReceiveType = 1,
                            MsgTitle = "卖家申请审核失败",
                            MsgText = msg
                        },
                        ReceiveUids = entity.uid.ToString()
                    };
                    PushMsgBiz.Instance.AddPushMsg(pushModel);

                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
                entity.is_do = 1;
                entity.do_time = DateTime.Now;
                if (dbcontext.SaveChanges() > 0)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                    //发送推送消息
                    AddPushMsgModel paramModel = new AddPushMsgModel
                    {
                        aDZ_Pushmessage = new ADZ_Pushmessage
                        {
                            MsgType = 2,
                            ReceiveType = 1,
                            MsgTitle = "卖家申请处理结果",
                            MsgText = "您提交的成为卖家申请已成功处理。"
                        },
                        ReceiveUids = entity.uid.ToString()
                    };
                    PushMsgBiz.Instance.AddPushMsg(paramModel);

                    if (dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name == entity.company_name && t.is_del == 0) == null)
                    {
                        ADZ_SupplierMaster supplierMaster = new ADZ_SupplierMaster
                        {
                            cityId = entity.company_cityid,
                            city_name = entity.company_cityname,
                            zhizhao_url = entity.company_img,
                            contact_name = entity.contact_name,
                            email = entity.email,
                            telephone = entity.telephone,
                            is_del = 0,
                            supplier_address = entity.company_address,
                            supplier_name = entity.company_name,
                            qq = entity.qq,
                            status = (int)SupplierStatus.AuditSucc,
                            supplier_type = (byte)entity.supplier_type
                        };
                        var saved_supplierMaster = dbcontext.ADZ_SupplierMaster.Add(supplierMaster);
                        dbcontext.SaveChanges();
                        entity.supplier_id = saved_supplierMaster.supplier_id;
                        dbcontext.SaveChanges();

                        //卖家审核通过，生成后台账号 by leev 2019-03-28
                        // daneel 2020-3-10 修改为使用用户手机号登录，而不是联系手机号登录

                        var userinfo = dbcontext.ADZ_MemberMaster.FirstOrDefault(t => t.uid == entity.uid);
                        var manager_mobile = userinfo.account_mobile;

                        string stroutput = string.Empty;
                        string pwd = Utils.GetRandom();
                        int ret = UserBiz.Instance.AddUserInfo(manager_mobile, entity.contact_name, Utils.Md5Encrypt(pwd, Encoding.UTF8), 1, entity.telephone, entity.email, entity.company_address, "", saved_supplierMaster.supplier_id, out stroutput);

                        //分配角色
                        int roleid = ConfigHelper.AppSetting<int>("sellerRole", 0);
                        if (roleid > 0)
                        {
                            //获取后台用户uid
                            Entity.UserInfo mgUser = UserBiz.Instance.GetUserInfo(manager_mobile);
                            if (mgUser != null && mgUser.uid > 0)
                                UserBiz.Instance.SetUserRole(mgUser.uid, roleid.ToString());
                        }

                        string managerUrl = ConfigHelper.AppSetting<string>("managerUrl");
                        //账号生成完，推送消息
                        string msg = string.Format("已为您分配供应商管理权限，管理地址：{0}，账号：{1}，初始密码：{2}，请及时更改密码以保证安全。", managerUrl, manager_mobile, pwd);
                        AddPushMsgModel pushModel = new AddPushMsgModel
                        {
                            aDZ_Pushmessage = new ADZ_Pushmessage
                            {
                                MsgType = 2,
                                ReceiveType = 1,
                                MsgTitle = "卖家后台账号",
                                MsgText = msg
                            },
                            ReceiveUids = entity.uid.ToString()
                        };
                        PushMsgBiz.Instance.AddPushMsg(pushModel);
                        //发短信
                        SmsBiz.Instance.SendMessage(manager_mobile, msg);
                        //发送业务消息
                        BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                        {
                            BusinessMsgType = (int)BusinessMsgEnum.UserApplySellPassed,
                            msg = $"卖家申请审核通过成为供应商，卖家名称{entity.company_name},分配账号{manager_mobile}，联系手机号{entity.telephone}",
                            msg_title = "卖家申请审核通过",
                            msg_url = $"/supplier/add/{entity.supplier_id}"
                        });
                    }
                }
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 买家升级
        /// <summary>
        /// 会员升级申请列表
        /// </summary>
        /// <param name="queryModel"></param>
        /// <returns></returns>
        [Description("会员升级申请列表")]
        [ViewPage]
        public ActionResult MemberUpApplyList(UpApplyQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            //条件筛选
            var queryable = dbcontext.View_MemberUpApply.Where(t => t.is_del == 0);
            if (queryModel.uid != -10)
                queryable = queryable.Where(t => t.uid == queryModel.uid);
            if (!string.IsNullOrWhiteSpace(queryModel.mobile))
                queryable = queryable.Where(t => t.account_mobile == queryModel.mobile);
            if (queryModel.beg_time.HasValue)
                queryable = queryable.Where(t => t.create_time >= queryModel.beg_time);
            if (queryModel.end_time.HasValue)
            {
                var end_time = queryModel.end_time.Value.AddDays(1);
                queryable = queryable.Where(t => t.create_time < end_time);
            }
            if (queryModel.is_do != -10)
                queryable = queryable.Where(t => t.is_do == queryModel.is_do);

            int rowcounts = queryable.Count();
            ViewData.Add("AllCount", rowcounts);
            var querylist = queryable.OrderByDescending(t => t.create_time)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<View_MemberUpApply> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<View_MemberUpApply>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [Description("会员升级处理")]
        [HttpPost]
        public ActionResult ToDoByUpApply(long id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var entity = dbcontext.ADZ_MemberUpApply.FirstOrDefault(t => t.seq_id == id);
            if (entity != null)
            {
                entity.is_do = 1;
                entity.do_time = DateTime.Now;
                entity.do_name = new CurrentUser().user.realName;
                if (dbcontext.SaveChanges() > 0)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                }
                //发送推送消息
                AddPushMsgModel paramModel = new AddPushMsgModel
                {
                    aDZ_Pushmessage = new ADZ_Pushmessage
                    {
                        MsgType = 2,
                        ReceiveType = 1,
                        MsgTitle = "会员升级处理结果",
                        MsgText = "您提交的会员升级请求已成功处理。"
                    },
                    ReceiveUids = entity.uid.ToString()
                };
                var result = PushMsgBiz.Instance.AddPushMsg(paramModel);
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 绑定业务员
        [Description("绑定业务员")]
        [HttpPost]
        public ActionResult BindManager(string ids, long manager_uid)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ResponseMsg resMsg = new ResponseMsg();
            if (string.IsNullOrWhiteSpace(ids))
            {
                resMsg.IsSuccess = false;
                resMsg.Message = $"传入的信息不对";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            if (ids.EndsWith(","))
                ids = ids.Substring(0, ids.Length - 1);
            StringBuilder strb = new StringBuilder();
            string[] id_arr = Regex.Split(ids, ",");
            foreach (var item in id_arr)
            {
                long num_id = ConvertHelper.TryPraseInt(item, 0);
                var obj = dbcontext.ADZ_MemberManager.FirstOrDefault(t => t.uid == num_id);
                if (obj != null)
                    dbcontext.ADZ_MemberManager.Remove(obj);

                if (num_id > 0)
                {
                    dbcontext.ADZ_MemberManager.Add(new ADZ_MemberManager
                    {
                        create_time = DateTime.Now,
                        manage_uid = manager_uid,
                        uid = num_id
                    });
                }
            }
            dbcontext.SaveChanges();

            resMsg.IsSuccess = true;
            resMsg.Message = $"处理完成";
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("移除业务员")]
        [HttpPost]
        public ActionResult UnBindManager(string ids)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ResponseMsg resMsg = new ResponseMsg();
            if (string.IsNullOrWhiteSpace(ids))
            {
                resMsg.IsSuccess = false;
                resMsg.Message = $"传入的信息不对";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            if (ids.EndsWith(","))
                ids = ids.Substring(0, ids.Length - 1);
            StringBuilder strb = new StringBuilder();
            string[] id_arr = Regex.Split(ids, ",");
            foreach (var item in id_arr)
            {
                long num_id = ConvertHelper.TryPraseInt(item, 0);
                var obj = dbcontext.ADZ_MemberManager.FirstOrDefault(t => t.uid == num_id);
                if (obj != null)
                    dbcontext.ADZ_MemberManager.Remove(obj);
            }
            dbcontext.SaveChanges();

            resMsg.IsSuccess = true;
            resMsg.Message = $"处理完成";
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}